package com.shopping_back.serviceImpl;

import com.shopping_back.mapper.UserAccountMapper;
import com.shopping_back.pojo.entity.MerchantInfo;
import com.shopping_back.mapper.MerchantInfoMapper;
import com.shopping_back.pojo.entity.UserAccount;
import com.shopping_back.pojo.vo.MerchantInfoVO;
import com.shopping_back.service.IMerchantInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

/**
 * <p>
 * 商家信息表 服务实现类
 * </p>
 *
 * @author Jack
 * @since 2025-07-12
 */
@Service
@RequiredArgsConstructor
public class MerchantInfoServiceImpl extends ServiceImpl<MerchantInfoMapper, MerchantInfo> implements IMerchantInfoService {

    private final MerchantInfoMapper merchantInfoMapper;

    private final UserAccountMapper userAccountMapper;

    @Override
    @Transactional
    public void updateMerchantInfo(Long userId, String shopName) {
        MerchantInfo merchant = merchantInfoMapper.selectById(userId);
        merchant.setShopName(shopName);
        this.updateById(merchant);
    }


    @Override
    @Transactional
    public Object saveMerchantInfo(MerchantInfoVO merchantInfo) {
        MerchantInfo merchant = new MerchantInfo();
        // 2. 校验必填字段
        if (StringUtils.isBlank(merchantInfo.getShopName())) {
            throw new IllegalArgumentException("店铺名称不能为空");
        }
        if (StringUtils.isBlank(merchantInfo.getBusinessLicense())) {
            throw new IllegalArgumentException("请上传营业执照");
        }

        // 3. 校验店铺名称唯一性（正确写法）
        if (merchantInfoMapper.existsByShopName(merchantInfo.getShopName())) {
            throw new IllegalArgumentException("店铺名称已被使用");
        }

        // 4. 设置状态（与前端统一）
        merchant.setUserId(merchantInfo.getUserId());
        merchant.setAuditStatus(0); // 改用字符串类型
        merchant.setCreateTime(LocalDateTime.now());
        merchant.setUpdateTime(LocalDateTime.now());
        merchant.setShopName(merchantInfo.getShopName());
        merchant.setBusinessLicense(merchantInfo.getBusinessLicense());
        merchantInfoMapper.insert(merchant);

        // 5. 保存到数据库（自动包含licenseUrl）
        return merchant;
    }


}
